//
//  FlipsideViewController.m
//  Megatlon
//
//  Created by Leandro Milmanda on 4/7/12.
//  Copyright 2012 www.lemil.com.ar. All rights reserved.
//

#import "FlipsideViewController.h"
#import "DisplayMap.h"
#import "SucursalCustomCell.h"


@implementation FlipsideViewController

@synthesize delegate, selectedSucursal, selectedCell;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //Show Ruedita de carga
    
    //Cargar el contenido desde la URL sync
    sucursalService = [SucursalesDao instance];
    
    if(![sucursalService isLoaded])
    {
        [sucursalService load];
    }
    
    //Sacar la ruedita
    
    [super viewDidLoad];
    
    UIImageView *imageview  = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_bar.png"]] autorelease];
    [imageview setBounds:(CGRectMake(0, 0, 1024, 42))];
    [navBar insertSubview:imageview atIndex:0];

    if([navBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        //iOS 5 new UINavigationBar custom background
        [navBar setBackgroundImage:imageview.image forBarMetrics: UIBarMetricsDefault];
    } 
    
}




- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [sucursalService getTotalSucursales];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier =  @"Cell";
    
    SucursalCustomCell *cell = (SucursalCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[SucursalCustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    } 
    

    
    NSDictionary *unaSucursal = [sucursalService getByIndex: indexPath.row];
       	
    cell.primaryLabel.text = [unaSucursal objectForKey:@"nombre"];

    int nro = [[unaSucursal objectForKey:@"id"] intValue];
    int estado = [[unaSucursal objectForKey:@"estado"] intValue];  

    NSDate *date = [NSDate date] ;
    NSCalendar *calendar = [NSCalendar currentCalendar ];
    NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit ;
    NSDateComponents *components = [calendar components:units fromDate:date];
    int weekday = [components weekday] - 1;
    if(weekday == 0) {
        weekday = 7;
    }
    int hour = [components hour];
    int minutes = [components minute];
    
    BOOL isOpened = [sucursalService isOpenedSucursalId:nro atDayNumber:weekday andTime:hour andMinutes:minutes];

    //NSLog(@"Flipsode Sucursal:%d , estado:%d, opened:%d",nro,estado,isOpened);
    
    switch (estado) {
        case 1:
        case 2:
            if(isOpened){
                cell.myImageView.image = [UIImage imageNamed:@"green-ball.png"];
                cell.secondaryLabel.text = [unaSucursal objectForKey:@"horario"] ; //[unaSucursal objectForKey:@"direccion"];
                cell.terciaryLabel.text = [unaSucursal objectForKey:@"direccion"];
            } else {
                cell.myImageView.image = [UIImage imageNamed:@"red-ball.png"];
                cell.secondaryLabel.text = [unaSucursal objectForKey:@"horario"] ; //[unaSucursal objectForKey:@"direccion"];
                cell.terciaryLabel.text = [unaSucursal objectForKey:@"direccion"];
            }
            break;
        default:
            cell.myImageView.image = [UIImage imageNamed:@"amber-ball.png"];
            cell.secondaryLabel.text = @"cerrada termporalmente " ;
            cell.terciaryLabel.text = [unaSucursal objectForKey:@"direccion"];
            break;
    }
    

    if(!cell.selected){    
        cell.selected = (self.selectedSucursal == nro);
        cell.highlighted = (self.selectedSucursal == nro);
    }

 
    return cell;
}


- (IBAction)done:(id)sender
{
    self.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;    
    [self.delegate flipsideViewControllerDidFinish:self];
}

- (void)dealloc {
    [selectedCell release];
    [super dealloc];
    
}
@end
